/** 
 * Projects JS handler
 */

function Projects()
{
  this.initialize = function() {
    var prj = this;
    this.loadTable();
    
    $(".upd_btn, .del_btn").bind("click", function(e) {
      var row = $(this).parent().parent();
      
      if ($(this).hasClass("del_btn"))
        prj.deleteProject(row);
      else
        prj.updateProject(row);
      
      e.stopPropagation();
      return false;
    });
    
    $("#projects_table_body .p_name").bind("click", function() {
      gsp.selectProject($(this).text());
    });
    
    $("#projects_add_new").bind("click", function() {
      $("#win_add_project").modal("show");
    });
    
    $("#win_add_project_import").bind("click", function() {
      gsp.scheduleTask(gsp.reloadPage, gsp);
    });
  }
  
  // Fill projects table
  this.loadTable = function() {
    var projects = gsp.projects;
    var rows = [];
    var update_btn = '<a href="javascript:null" class="upd_btn">Update</a>';
    var delete_btn = '<a href="javascript:null" class="del_btn">Delete</a>';

    for (var k in projects) {
      var p = projects[k];
      var selected = (p.selected) ? " <span class='label notice'>Selected</span>" : "";
      var name = "<td><span class='p_name'>"+ p.name +"</span>"+ selected +"</td>";
      var date = "<td class='p_updated'>"+ prettyDate(p.updated) +"</td>";
      var actions = "<td>" + update_btn + " | " + delete_btn + "</td>";
      
      rows.push("<tr>" + name + date + actions + "</tr>");
    }
    
    $("#projects_table_body").html(rows.join("\n"));
  };
  
  // Delete repository and database record
  this.deleteProject = function(row) {
    var name = row.find("span.p_name").text();
    
    if (!confirm("Do you want to remove "+ name +"?"))
      return;
    
    gsp.request("project", {"a": "delete", "name": name}, function() {
      row.hide(500);
      gsp.refreshProjects();
    });
    
    return false;
  }
  
  // Update local repository from remote source
  this.updateProject = function(row) {
    // If project is updating now, do nothing
    if (row.find(".label.upd").length)
      return false;
    
    var name = row.find("span.p_name").text();
    row.find("td:first-child").append(" <span class='label upd'>Updating&hellip;</span>");
    
    gsp.request("project", {"a": "update", "name": name}, function() {
      row.find(".label.upd").remove();
      row.find("td.p_updated").html("just now");
    });
  }
  
  return false;
}


var loader = function() { (new Projects()).initialize(); }
